<template>
    <div @click="closeDiloagBox" class="audience-container">
        <loading v-show="isLoading"/>
        <div class="audience-tips">
            <span class="iconfont icon-focus"></span><span>&nbsp;精准定位受众群体，将提高您的广告效果</span>
        </div>
        <div>
            <el-form
                    :model="editAudienceForm"
                    ref="editAudienceForm"
                    label-width="100px">

                <!--1：选择受众-->
                <el-form-item  v-if="adPlatform == 'Facebook'"  label="选择受众：" class="adv-form-item">
                    <div @click.self.stop="audienceTabsShow" class='name-tag-box'>
                        <el-tag
                            v-if="editAudienceForm.nameList.name"
                            :closable="true"
                            @close="closeListTag(0,'name')"
                            :title="editAudienceForm.nameList.name"
                            class="name-tag">
                            {{editAudienceForm.nameList.name|longTagName}}
                        </el-tag>
                        <span @click.self.stop="dialogNameVisible=true" class="name-tag-icon el-icon-arrow-down"></span>
                    </div>
                    <!-- 选项 -->
                    <div @click.stop="" v-show="dialogNameVisible" class="dialog-name-box">
                        <el-tabs v-model="activeName" @tab-click="handleClick">
                            <el-tab-pane v-for="(tab,i) in audienceTabs" :key="i" :label="tab.label" :name="tab.name" style="padding-bottom:15px;max-height:300px;overflow:auto;">
                                <el-popover
                                  v-for="(item,n) in tab.list" :key="n"
                                  placement="right-start"
                                  width="190"
                                  trigger="hover"
                                  
                                  >
                                    <div class="adv-tooltip" style="text-align:left">
                                        <div class="tooltip-name"><span>{{item.name}}</span></div>
                                        <div><span class="tooltip-label">类型：</span><span class="tooltip-info">{{item.type|audienceTypeFilter}}</span></div>
                                        <div><span class="tooltip-label">预计覆盖人数：</span><span>{{item.reach}}</span></div>
                                        <div v-if="item.from"><span class="tooltip-label">来源：</span><span class="tooltip-info">{{item.localId}}</span></div>
                                    </div>
                                    <el-row  slot="reference"  class='active-row'>
                                        <div class="audience-info" @click.stop="handleAudience(item,'name')">
                                            <el-col class="active-name" :span='12'>{{item.name}}</el-col>
                                            <el-col class="active-type" :span='12'>{{item.type | audienceTypeFilter}}</el-col>
                                        </div>
                                    </el-row>
                                </el-popover>
                                <div v-if='i===0 && !audienceTabs[0].list.length &&saveNo' class="no-audence">保存的受众(无数据)</div>
                                <div v-if='i===1 && !audienceTabs[1].list.length &&diyNo' class="no-audence">自定义受众(无数据)</div>
                                <div v-if='i===2 && !audienceTabs[2].list.length &&sameNo' class="no-audence">类似受众(无数据)</div>

                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </el-form-item>

                <!--2：位置-->
                <div v-show="editAudienceForm.addr.include.length ==0 &&keywordsEmpty" class="iconfont location-tips"><span class="icon-tip"></span><span>{{locationMessage}}</span></div>
                <div class="adv-form-item">
                    <div class="el-form-item__label required-label">
                        <span>位置</span><span class="required-tip">&nbsp;*</span><span>：</span>
                    </div>
                    <div class='tag-box-border' :class="editAudienceForm.addr.include.length ==0 &&keywordsEmpty?'tag-box-error':''">
                        <el-row>
                            <el-col :span='3' class='tag-box-title'><span class="iconfont icon-location-include" style="font-size:14px;"></span>&nbsp;包括：</el-col>
                            <el-col :span='21' class='tag-box-inner'>
                                <span v-show="editAudienceForm.addr.include.length ==0">-</span>
                                <el-tag
                                        v-for="(tag,index) in editAudienceForm.addr.include"
                                        :closable="true"
                                        :key="index"
                                        @close="closeListTag(index,'addrinclude')"
                                        class="adv-tag"
                                >
                                    {{tag.type=='country'||tag.type=='国家'?tag.name:(tag.name+ ',' +tag.country)}}
                                </el-tag>
                            </el-col>
                        </el-row>
                        <div class="tag-line"></div>
                        <el-row v-show="addrExcludeShow || editAudienceForm.addr.exclude.length > 0">
                            <el-col :span='3' class='tag-box-title' style="max-width:80px;">
                                <span class="iconfont icon-hebingxingzhuang1" style="font-size:14px;color:#FF3526;"></span> <span>&nbsp;不包括：</span>
                            </el-col>
                            <el-col :span='21' class='tag-box-inner'>
                                <span v-show="editAudienceForm.addr.exclude.length ==0">-</span>
                                <el-tag
                                        v-for="(tag,index) in editAudienceForm.addr.exclude"
                                        :closable="true"
                                        :key="index"
                                        @close="closeListTag(index,'addrexclude')"
                                        class="adv-tag"
                                >
                                    {{tag.name}}
                                </el-tag>
                            </el-col>
                        </el-row>
                        <div class="tag-line" v-show="addrExcludeShow || editAudienceForm.addr.exclude.length > 0"></div>
                        <el-row>
                            <el-col :span='24'>
                                <span class="label-title">添加地区</span>
                                <el-select v-model="addrType" size="small" placeholder="请选择" class="inline-input-select" style="width:90px">
                                    <el-option label="包括" value="include"></el-option>
                                    <el-option label="不包括" value="exclude"></el-option>
                                </el-select>
                                <span class="label-title">:</span>
                                <el-autocomplete
                                        custom-item="addr-item"
                                        class="inline-input"
                                        icon="search"
                                        size="small"
                                        v-model="addrInput"
                                        :fetch-suggestions="queryAddrSearch"
                                        placeholder=""
                                        :trigger-on-focus="false"
                                        @select="handleAddrSelect"
                                >
                                </el-autocomplete>
                            </el-col>
                        </el-row>
                    </div>
                </div>

                <!--fb语言-->
                <div  v-if="adPlatform == 'Facebook'" label="语言：" class="adv-form-item">
                    <div class="el-form-item__label required-label">
                        <span>语言：</span>
                    </div>
                    <div class='tag-box-border'>
                        <el-row>
                            <el-col :span='3' class='tag-box-title'>包括：</el-col>
                            <el-col :span='21' class='tag-box-inner'>
                                <span v-show="editAudienceForm.language.length ==0">-</span>
                                <el-tag
                                        v-for="(tag,index) in editAudienceForm.language"
                                        :closable="true"
                                        :key="index"
                                        @close="closeListTag(index,'language')"
                                        class="adv-tag"
                                >
                                    {{tag.name}}
                                </el-tag>
                            </el-col>
                        </el-row>
                        <div class="tag-line"></div>
                        <el-row>
                            <el-col :span='24'>
                                <span class="label-title">添加语言：</span>
                                
                                <el-autocomplete
                                        class="inline-input"
                                        icon="search"
                                        size="small"
                                        v-model="languageInput"
                                        :fetch-suggestions="queryLanguageSearch"
                                        placeholder=""
                                        :trigger-on-focus="false"
                                        @select="handleLanguageSelect"
                                >
                                </el-autocomplete>
                            </el-col>
                        </el-row>
                    </div>
                </div>

                <!--Gg语言-->
                <div v-show="adPlatform == 'Google' && editAudienceForm.language.length ==0 &&keywordsEmpty" class="iconfont location-tips"><span class="icon-tip"></span><span>至少包含一种语言</span></div>
                <div  v-if="adPlatform == 'Google'" class="adv-form-item">
                    <div class="el-form-item__label required-label"  style="width: 100px;text-align:right">
                        <span>语言</span><span class="required-tip">&nbsp;*</span><span>：</span>
                    </div>
                    <div class='tag-box-border el-form-item__content' :class="editAudienceForm.language.length ==0 &&keywordsEmpty?'tag-box-error':''" style="margin-left: 100px;">
                        <el-row>
                            <el-col :span='3' class='tag-box-title'>包括：</el-col>
                            <el-col :span='21' class='tag-box-inner'>
                                <span v-show="editAudienceForm.language.length ==0">-</span>
                                <el-tag
                                        v-for="(tag,index) in editAudienceForm.language"
                                        :closable="true"
                                        :key="index"
                                        @close="closeListTag(index,'language')"
                                        class="adv-tag"
                                >
                                    {{tag.name}}
                                </el-tag>
                            </el-col>
                        </el-row>
                        <div class="tag-line"></div>
                        <el-row>
                            <el-col :span='24'>
                                <span class="label-title">添加语言：</span>
                                <el-select @change="ggLanguageSelect" v-model="languageInput" filterable size="small" class="inline-input">
                                    <el-option
                                      v-for="item in ggLanguageList"
                                      :key="item.name"
                                      :label="item.name"
                                      :value="item.name">
                                    </el-option>
                                  </el-select>
                            </el-col>
                        </el-row>
                    </div>
                </div>


                <div v-if="adPlatform == 'Facebook'" label="性别：" class="adv-form-item">
                    <div class="el-form-item__label required-label">
                        <span>性别：</span>
                    </div>
                    <div class='tag-box-border'>
                        <el-radio style="width:100px;" class="radio" v-model="editAudienceForm.gender" :label="null">全部</el-radio>
                        <el-radio style="width:100px;" class="radio" v-model="editAudienceForm.gender" label="1">男性</el-radio>
                        <el-radio style="width:100px;" class="radio" v-model="editAudienceForm.gender" label="2">女性</el-radio>
                    </div>
                </div>

                <div v-if="adPlatform == 'Facebook'" label="年龄：" class="adv-form-item">
                    <div class="el-form-item__label required-label">
                        <span>年龄：</span>
                    </div>
                    <div class='tag-box-border'>
                        <span class="label-title">从</span>
                        <el-input size="small" min="13" max="65" v-model.number="editAudienceForm.age.start" @blur="autoAge" type="number" style="width:70px"></el-input>
                        <span class="label-title">到</span>
                        <el-input size="small" min="13" max="65" v-model.number="editAudienceForm.age.end" @blur="autoAge" type="number" style="width:70px"></el-input>
                    </div>
                </div>

                <div v-if="adPlatform == 'Facebook'" class="adv-form-item" style="min-height:40px;">
                    <div class="el-form-item__label required-label">
                        <span>高级设置：</span>
                    </div>
                    <el-switch
                            style="margin-top:10px;"
                            v-model="switchValue"
                            on-text=""
                            off-text="">
                    </el-switch>
                    <div v-show="switchValue" >
                        <div label="" class="adv-form-item more-box-border">
                            <div>
                                <div class="el-form-item__label more-required-label">
                                    <span>细分定位：</span>
                                </div>
                                <div class="more-form-item">
                                    <el-row>
                                        <el-col :span='24'>
                                            <el-select size="small" v-model="positionType" placeholder="请选择" style="width:90px;">
                                                <el-option label="包含" value="1"></el-option>
                                                <el-option label="不包含" value="2"></el-option>
                                            </el-select>
                                            <span class="label-title">:</span>
                                            <el-autocomplete
                                                    popper-class="position-autocomplete"
                                                    custom-item="position-item"
                                                    class="inline-input-big"
                                                    size="small"
                                                    v-model="positionInput"
                                                    :fetch-suggestions="queryPositionSearch"
                                                    placeholder="添加人口统计数据、兴趣和行为"
                                                    :trigger-on-focus="true"
                                                    @select="handlePositionSelect"
                                            >
                                            </el-autocomplete>
                                            <div class="append-btn">
                                                <span class="el-icon-search" style="color:#BFCBE0;"></span>
                                                <span @click.stop="getTreeJson" class="pre-view">预览</span>
                                            </div>
                                        </el-col>

                                        <el-col>
                                            <!-- 预览 -->
                                            <div @click.stop="" v-if="dialogPreviewVisible && positionType == '1'" class="dialog-preview-box">
                                                <div v-if="positionShow" style="height:80px;line-height:80px;text-align:center;"><i class="el-icon-loading" style="font-size:30px;color:#999;"></i></div>
                                                <div v-else class="preview-tree-select" >
                                                    <el-tree
                                                        empty-text=''
                                                        :data="positionPreviewTree"
                                                        :props="positionPreviewTreeProps"
                                                        :render-content="renderContent">
                                                    </el-tree>
                                                </div>

                                            </div>

                                            <div @click.stop="" v-if="dialogPreviewVisible && positionType == '2'" class="dialog-preview-box">
                                                <div v-if="positionShow" style="height:80px;line-height:80px;text-align:center;"><i class="el-icon-loading" style="font-size:30px;color:#999;"></i></div>
                                                <div v-else class="preview-tree-select">
                                                    
                                                    <el-tree
                                                            empty-text=''
                                                            :data="positionExcludePreviewTree"
                                                            :props="positionPreviewTreeProps"
                                                            :render-content="renderContent">
                                                    </el-tree>
                                                </div>
                                            </div>
                                        </el-col>
                                    </el-row>

                                    <el-row class="tag-border-top">
                                        <el-col :span='3' class='tag-box-title'>包含：</el-col>
                                        <el-col :span='21' class='tag-box-inner'>
                                            <span v-show="editAudienceForm.position.include.length ==0">-</span>
                                            <el-tag
                                                    v-for="(tag,index) in editAudienceForm.position.include"
                                                    :closable="true"
                                                    :key="index"
                                                    @close="closeListTag(index,'positioninclude')"
                                                    class="adv-tag"
                                            >
                                                {{tag.name}}
                                            </el-tag>
                                        </el-col>
                                    </el-row>

                                    <div class="tag-line-black"></div>

                                    <el-row>
                                        <el-col :span='3' class='tag-box-title'>不包含：</el-col>
                                        <el-col :span='21' class='tag-box-inner'>
                                            <span v-show="editAudienceForm.position.exclude.length ==0">-</span>
                                            <el-tag
                                                    v-for="(tag,index) in editAudienceForm.position.exclude"
                                                    :closable="true"
                                                    :key="index"
                                                    @close="closeListTag(index,'positionexclude')"
                                                    class="adv-tag"
                                            >
                                                {{tag.name}}
                                            </el-tag>
                                        </el-col>
                                    </el-row>
                                    <div class="tag-line-black"></div>
                                </div>
                            </div>

                            <div style="margin-top:15px;">
                                <div class="el-form-item__label more-required-label">
                                    <span>关系：</span>
                                </div>
                                <div class="more-form-item">
                                    <el-row>

                                        <el-col :span='24' style="margin-bottom:10px;">
                                            <el-checkbox @change="checkChange($event,'CONNECTION')" v-model="connectionCheck.CONNECTION" class="radio" label="CONNECTION">主页点赞用户</el-checkbox>
                                            <el-checkbox @change="checkChange($event,'FRIEND')" v-model="connectionCheck.FRIEND" class="radio" label="FRIEND">主页点赞用户好友</el-checkbox>
                                            <el-checkbox @change="checkChange($event,'EXCLUDE')" v-model="connectionCheck.EXCLUDE" class="radio" label="EXCLUDE">排除主页点赞用户</el-checkbox>
                                        </el-col>
                                        <el-col :span='24' class="tag-box-homepage" v-show="editAudienceForm.relationship">
                                            <span v-for="(item,index) in homepageList" :key="index" class="homepage-tag">
                                              <el-checkbox v-model="item.check" @change="pageListCheck(item)" :label="item.name"></el-checkbox>
                                          </span>
                                          <div v-if="!homepageList.length" class="no-homepage">请先创建一个Facebook主页 <a target="_blank" href="https://www.facebook.com/pages/create/?ref_type=pages_you_admin">创建主页</a></div>
                                        </el-col>
                                    </el-row>
                                </div>
                            </div>

                            <div v-if="type == 'new'" style="padding-left:90px;margin-top:10px;line-height:11px;">
                                <div v-if="replaceBtnShow" class="btn_common_white" style="font-size:12px;" @click="replaceShow">替换已有受众</div>
                                <div class="btn_common_yellow" style="margin-left:8px;font-size:12px;" @click="saveShow">保存为新受众</div>
                            </div>
                        </div>
                    </div>
                </div>

                

                <!--2：关键词-->
                <div v-show="editAudienceForm.keywords.include.length == 0 && adPlatform == 'Google' && keywordsEmpty" class="iconfont location-tips"><span class="icon-tip"></span><span>至少包含一个关键词</span></div>
                <div v-if="adPlatform == 'Google'" label="关键词：" class="adv-form-item">
                    <div class="el-form-item__label required-label"  style="width: 100px;text-align:right">
                        <span>关键词</span><span class="required-tip">&nbsp;*</span><span>：</span>
                    </div>
                    <div class='tag-box-border' :class="keywordsEmpty && editAudienceForm.keywords.include.length ==0?'tag-box-error':''">
                        <el-row>
                            <el-col :span='3' class='tag-box-title' style="height:36px;line-height:36px;">包括：</el-col>
                            <el-col :span='21' class='tag-box-inner'>
                                <span v-show="editAudienceForm.keywords.include.length ==0"  style="height:36px;line-height:36px;">-</span>
                                <KeyWordsTag type="include" />
                            </el-col>
                        </el-row>
                        <div class="tag-line"></div>
                        <el-row v-show="keywordsExcludeShow || editAudienceForm.keywords.exclude.length > 0">
                            <el-col :span='3' class='tag-box-title' style="max-width:80px;height:36px;line-height:36px;">
                                <span>不包括：</span>
                            </el-col>
                            <el-col :span='21' class='tag-box-inner'>
                                <span v-show="editAudienceForm.keywords.exclude.length ==0" style="height:36px;line-height:36px;">-</span>
                                <KeyWordsTag type="exclude" />
                                
                            </el-col>
                        </el-row>
                        <div v-show="keywordsExcludeShow || editAudienceForm.keywords.exclude.length > 0" class="tag-line"></div>
                        <el-row>
                            <el-col :span='24'>
                                <el-select v-model="keywordsType" size="small" placeholder="请选择" class="inline-input-select" style="width:90px">
                                    <el-option label="包括" value="include"></el-option>
                                    <el-option label="不包括" value="exclude"></el-option>
                                </el-select>
                                <span> : </span>
                                <el-input
                                    style="width:320px;"
                                    v-model.trim="keywordsInput" 
                                    class="inline-input" 
                                    placeholder="输入关键词回车或选择添加"
                                    @keyup.enter.native="enterKeyWords"
                                    icon="close"
                                    size="small"
                                    :on-icon-click="clearKeywordsInput"
                                    @blur="focusKeywords = false"
                                    @focus="initKeywordsList"
                                ></el-input>
                                <el-button type="primary" size="small" @click.stop="keyWordsSearch" style="margin-left:5px;">查询</el-button>
                            </el-col>

                            <el-col>
                                <!-- 预览 -->
                                <div @click.stop="" v-if="dialogKeywordsVisible" class="dialog-keywords-box">
                                    <div v-if="keywordsShow" style="height:80px;line-height:80px;text-align:center;"><i class="el-icon-loading" style="font-size:30px;color:#999;"></i></div>
                                    <div v-if="!keywordsShow && !preKeywordsList.length" style="height:80px;line-height:80px;text-align:center;">无匹配的关键词</div>
                                    <div v-else class="preview-tree-select" >
                                        <div v-for="item in preKeywordsList" @click.stop="keyWordsSelect($event,item)" class="keywords-list">
                                            <div :title="item.value" class="key-item key-value">{{item.value}}</div>
                                            <div class="key-item key-comper">竞争度：{{item.competition|compeFilter}}</div>
                                        </div>
                                    </div>

                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>


                <div label="设备：" class="adv-form-item">
                    <div class="el-form-item__label required-label">
                        <span>设备</span><span class="required-tip">&nbsp;*</span><span>：</span>
                    </div>
                    <div class='tag-box-border'>
                        <el-radio v-if="adverPlan!='主页赞'" class="radio device-radio" v-model="adverLayout.device" label="all">所有设备</el-radio>
                        <el-radio class="radio device-radio" :disabled="deviceDisable || adPlatform=='Google'" v-model="adverLayout.device" label="pc">仅桌面设备</el-radio>
                        <el-radio v-if="adverPlan!='主页赞'" class="radio device-radio" :disabled="deviceDisable || adPlatform=='Google'" v-model="adverLayout.device" label="mb">仅移动设备</el-radio>
                    </div>
                </div>
                <el-form-item v-if="type == 'new'" label="" class="adv-form-item" style="margin-bottom:100px;">
                    <el-button v-if="!nexting" @click="nextStep" class="bd-next-btn" type="primary">下一步</el-button>
                    <el-button v-else class="bd-next-btn" type="primary" :loading="true">验证中</el-button>
                </el-form-item>

            </el-form>
        </div>



        <el-dialog title="保存为新受众" class="min-width-dialog" size="tiny" v-model="dialogSaveVisible">
            <div class="form-row">
                <span class="form-label">
                    <span>受众名称</span><span class="required-tip">&nbsp;*</span><span>：</span>
                </span>
                <el-input class="el-input-title" @blur="Autocomplete"  :maxlength="50" size="small" style="width:55%;" v-model.trim="editAudienceForm.name"></el-input>
                <span class="adc-tips string-count-tip" @click="edit($event)">{{nowLength}}</span>
            </div>

            <div slot="footer">
                <div class="btn_common_white btn_common_small" style="line-height:17px;" @click="dialogSaveVisible = false">取消</div>
                <div class="btn_common_yellow btn_common_small btn-common" style="line-height:17px;" @click="saveAudience">确定</div>
            </div>
        </el-dialog>

        <el-dialog class="min-width-dialog"  title="替换受众" size="tiny" v-model="dialogReplaceVisible">
            <div class="tip-wrapper">
                <div class="tip-left">
                    <i class="iconfont icon-tip" style="font-size:30px"></i>
                </div>
                <div class="tip-right">
                    <span class="tip-title">替换受众</span>
                    <span class="tip-txt">确定替换受众：<span>{{editAudienceForm.nameList.name}}</span>吗？</span>
                </div>
            </div>
            <div slot="footer">
                <div class="btn_common_white btn_common_small" style="line-height:17px;"  @click="dialogReplaceVisible = false">取消</div>
                <div class="btn_common_yellow btn_common_small btn-common" style="line-height:17px;" @click="replaceAudience">确定</div>
            </div>
        </el-dialog>

    </div>
</template>
<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios'
    import { mapGetters, mapActions, mapMutations} from 'vuex';
    import { Switch,Tree,Autocomplete,Radio,Tabs,TabPane,ButtonGroup,Icon,Button,Checkbox,Table,TableColumn,Dialog,Input,Form,FormItem,Tag,Select,Option,MessageBox,Message,Popover } from 'element-ui'
    import KeyWordsTag from '~components/create/keyWordsTag.vue'
    import ToggleButton from '~/components/toggleButton.vue'
    import loading from '~/components/loading.vue'
    import { highLighted,charCodeLen } from '~/assets/js/global'

    Vue.use(Switch)
    Vue.use(Tree)
    Vue.use(Autocomplete)
    Vue.use(Radio)
    Vue.use(Tabs)
    Vue.use(TabPane)
    Vue.use(Table)
    Vue.use(Checkbox)
    Vue.use(TableColumn)
    Vue.use(ButtonGroup)
    Vue.use(Icon)
    Vue.use(Button)
    Vue.use(Input)
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Tag)
    Vue.use(Dialog)
    Vue.use(Popover)
    
    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;

    Vue.component('position-item', {
        functional: true,
        render: function (h, ctx) {
          var item = ctx.props.item;
          return h('li', ctx.data, [
            h('div', { attrs: { style: 'float:left; width:65%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;' } }, [item.value]),
            h('div', { attrs: { style: 'float:right; width:35%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align:right;color:#bbb' } }, [item.type])
          ]);
        },
        props: {
          item: { type: Object, required: true }
        }
    });

    Vue.component('addr-item', {
        functional: true,
        render: function (h, ctx) {
          var item = ctx.props.item;
          if(item.type == 'country' || item.type == '国家'){
            return h('li', ctx.data, [
                h('div', { attrs: { style: 'float:left; width:65%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;' } }, [item.value]),
                h('div', { attrs: { style: 'float:right; width:35%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align:right;color:#bbb' } }, [item.type])
              ]);

          }else{
            return h('li', ctx.data, [
                h('div', { attrs: { style: 'float:left; width:70%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;' } }, [item.value,',',item.country]),
                h('div', { attrs: { style: 'float:right; width:30%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;text-align:right;color:#bbb' } }, [item.type])
              ]);
          }
          
        },
        props: {
          item: { type: Object, required: true }
        }
    });


    
    export default{
        components: {
            ToggleButton,
            KeyWordsTag,
            loading
        },
        props:{
            'type' : {//判断是编辑还是新增new edit
                default:'new'
            }
        },
        data () {
            return {
                connectionCheck:{
                    CONNECTION:false,
                    FRIEND:false,
                    EXCLUDE:false
                },
                audienceId:null,
                isLoading: false,
                positionShow: true,
                keywordsShow:true,
                nexting: false,
                requireName:false,
                AudienceType:"已保存受众",
                deviceDisable:false,
                isSaved:false,
                //关系
                switchValue:false,
                saveNo: false,
                diyNo: false,
                sameNo: false,
                //细分定位预览
                positionPreviewTree:[],
                positionExcludePreviewTree:[],
                positionPreviewTreeProps: {
                    label: 'path',
                    children: 'children'
                },
                //位置
                locationEmpty:false,
                keywordsEmpty:false,
                //主页列表
                //homepageList:[],
                systemShow:false,
                activeName:'first',
                //表单信息
                addrInput:'',
                addrType:'include',
                addrExcludeShow : false,
                keywordsType:'include',
                keywordsInput:'',
                preKeywordsInput:'',
                preKeywordsList:[],
                keywordsExcludeShow:false,
                languageInput:'',
                positionType:'1',
                positionInput:'',
                deviceInput:'',
                replaceBtnShow:false,
                ggLanguageList:[],
                initFbAddr:[],
                initFbLanguage:[],
                initFbPositon: [],
                initGgAddr:[],
                initGgLanguage:[],
                initkeywords:[],
                newEditAudienceForm:{
                    name:null,     //受众名称
                    nameList:{}, //选择的受众信息
                    addr:{      //位置
                        include:[], //包括
                        exclude:[]  //不包括
                    },
                    language:[],   //语言
                    gender:null,  //性别
                    age:{     //年龄
                        start:"21",
                        end:"65"
                    },
                    position:{    //细分定位
                        include:[],
                        exclude:[]
                    },
                    relationship:null, //关系CONNECTION
                    checkHomePage:[],//已选主页{"value":"主页1"}
                    keywords:{      //关键词
                        include:[], //包括
                        exclude:[]  //不包括
                    },
                    reach:null
                },
                checked:true,
                dialogSaveVisible:false,
                dialogReplaceVisible:false, //替换受众
                dialogNameVisible:false, //已有受众
                dialogPreviewVisible:false,//预览
                dialogKeywordsVisible:false,
                focusKeywords:false,
                audienceTabs:[
                    {
                        label: "保存的受众",
                        name: "first",
                        list:[]
                    },{
                        label: "自定义受众",
                        name: "second",
                        list:[]
                    },{
                        label: "类似受众",
                        name: "third",
                        list:[]
                    }
                ],
                locationMessage:'请至少选择一个位置',
                nowLength: 50,
                dataName: '',
                stepCreated: false,
                timer : null,
                initEnd : false,
                homePageDisable: true,
                urlKeywordsList:[],
                nowUrl: '',
                queryedUrl: false
            }
        },
        watch:{
            'editAudienceForm.addr.include'(){
                if(this.editAudienceForm.addr.exclude.length){
                    this.locationMessage = '请至少选择一个包括的位置'
                }else{
                    this.locationMessage = '请至少选择一个位置'
                }
                if(this.adPlatform == 'Facebook'&& this.initEnd && this.editAudienceForm.addr.include.length){
                    this.fbAudienceCount(true);
                }else if(this.adPlatform == 'Google'&& this.initEnd){
                    this.ggAudienceCount(true);
                }
            },
            'editAudienceForm.addr.exclude'(){
                if(this.editAudienceForm.addr.exclude.length){
                    this.locationMessage = '请至少选择一个包括的位置'
                    return false;
                }else{
                    this.locationMessage = '请至少选择一个位置'
                    return false;
                }
                if(this.adPlatform == 'Facebook'&& this.initEnd){
                    this.fbAudienceCount(true);
                }else if(this.adPlatform == 'Google'&& this.initEnd){
                    this.ggAudienceCount(true);
                }
            },
            'editAudienceForm.name'(){
                this.nowLength = 50 - charCodeLen(this.editAudienceForm.name);
                this.requireName = this.editAudienceForm.name?false:true;
            },
            'editAudienceForm.language'(){
                if(this.adPlatform == 'Facebook'&& this.initEnd){
                    this.fbAudienceCount(true);
                }else if(this.adPlatform == 'Google'&& this.initEnd){
                    this.ggAudienceCount(true);
                }
            },
            'editAudienceForm.gender'(){
                this.fbAudienceCount(true);
            },
            'editAudienceForm.position.include'(){
                if(this.adPlatform == 'Facebook'&& this.initEnd){
                    this.fbAudienceCount(true);
                }
            },
            'editAudienceForm.keywords.include'(){
                this.initEnd = true;
                if(this.adPlatform == 'Google' && this.editAudienceForm.keywords.include.length){
                    this.ggAudienceCount(true);
                }else{
                    let item = {
                        click:"",
                        cost:"",
                        impressions:""
                    }
                    this.$store.commit("GGAUDIENCE_COUNT_TIPS", {item})
                }
            },
            'editAudienceForm.keywords.exclude'(){
                if(this.adPlatform == 'Google'&& this.initEnd){
                    this.ggAudienceCount(true);
                }
            },
            'editAudienceForm.relationship'(){
                //console.log(this.editAudienceForm.relationship,this.editAudienceForm.checkHomePage)
                this.homePageDisable = false;
                this.connectionCheck = {
                    CONNECTION:false,
                    FRIEND:false,
                    EXCLUDE:false
                }
                if(this.editAudienceForm.relationship){
                    let connection = this.editAudienceForm.relationship;
                    this.connectionCheck[connection] = true;
                }
                if(this.editAudienceForm.relationship === null){
                    this.editAudienceForm.checkHomePage = [];
                    let len = this.homepageList.length;
                    for (let i = 0; i < len; i++) {
                        this.homepageList[i].check = false;
                    }
                }
                if(this.adPlatform == 'Facebook'&& this.initEnd){
                    if(this.editAudienceForm.relationship && !this.editAudienceForm.checkHomePage.length){
                        return;
                    }else if(!this.editAudienceForm.relationship && this.editAudienceForm.checkHomePage.length){
                        return;
                    }
                    this.fbAudienceCount(true);
                }
                
            },
            'editAudienceForm.checkHomePage'(){
                if(this.adPlatform == 'Facebook'&& this.initEnd){
                    if(this.editAudienceForm.relationship && !this.editAudienceForm.checkHomePage.length){
                        return;
                    }else if(!this.editAudienceForm.relationship && this.editAudienceForm.checkHomePage.length){
                        return;
                    }
                    this.fbAudienceCount(true);
                }
            },
            'adverLayout.device'(){
                if(this.adPlatform == 'Facebook'&& this.initEnd){
                    this.fbAudienceCount(true);
                }
            },
            adPlatform(){
                this.initPlatDate()
            },
            addrType(){
                this.addrExcludeShow = true;
            },
            keywordsType(){
                this.keywordsExcludeShow = true;
            },
            switchValue(){
                if(this.positionPreviewTree.length == 0){
                    //this.getPositionTree();
                }
                if(this.switchValue && this.editAudienceForm.position.include.length ==0){
                    
                    this.editAudienceForm.position.include = this.initFbPositon;
                }
            },
            keywordsInput(){
                //this.dialogKeywordsVisible = this.keywordsInput?false:true;
                if(this.keywordsInput){
                    return;
                }else{
                    this.keyWordsSearch()
                }
            }
        },
        computed : {
            ...mapGetters([
                "adverPlan",
                "audienceInfo",
                "editAudienceForm",
                "adverLayout",
                "adPlatform",
                "createdStep",
                "homepageList",
                "adverUrl"
            ])
        },
        filters:{
            audienceTypeFilter(value){
                switch(value){
                    case "SAVED":
                        return "保存受众";
                        break;
                    case "LOOKALIKE":
                        return "类似受众";
                        break;
                    case "ENGAGEMENT":
                        return "主页互动受众";
                        break;
                    case "CUSTOM":
                        return ",客户文件受众";
                        break;
                }
            },
            longTagName(value){
                if(value.length > 26){
                    return value.substr(0,26)+'...'
                }else{
                    return value
                }
            },
            compeFilter(value){
                switch (value){
                    case 'HIGH':
                        return '高';
                        break;
                    case 'MIDEL':
                        return '中';
                        break;
                    case 'LOW':
                        return '低';
                        break;
                    default:
                        return value;
                }
            }
        },
        created() {
            //this.$route.query.id
            // if(this.adPlatform == 'Facebook'){
            //     this.queryPageList();
            // }
            
            //谷歌语言列表
            if(this.adPlatform == 'Google'){
                this.$store.dispatch('ggLanguageList')
                    .then((res)=>{
                        if(res && res.data&& res.data.data){
                            let list = res.data.data;
                            list.forEach((n,i)=>{
                                n.value = n.name;
                                n.key = n.platformFlag;
                            });
                            this.ggLanguageList = list;
                        }
                    })
            }

            /***
                缓存或默认值
            **/

            if(this.type == 'new'){
                if(this.adPlatform == 'Facebook'){
                    this.queryPageList();
                    
                    this.$store.dispatch("adGroupCacheValue") //fb缓存--默认值
                    .then((res)=>{
                        if(res && res.data &&res.data.data){
                            let result = res.data.data.savedAudience;
                            this.initFbAddr = result.places;
                            this.initFbLanguage = result.locales;
                            this.initFbPositon = result.suggestions;
                        }
                        this.initPlatDate()
                    })
                    //this.editAudienceForm.addr.include=[{name:'s'}]
                }else{
                    this.$store.dispatch("ggGroupCacheValue") //谷歌缓存--默认值
                    .then((res)=>{
                        if(res && res.data &&res.data.data){
                            let result = res.data.data.audience;
                            this.initGgAddr = result.places;
                            this.initGgLanguage = result.languages;
                        }
                        this.initPlatDate()
                    })
                }
            }

            //自動名稱
            let time = new Date();
            let year = (time.getFullYear()+"").substr(2,2);
            let month = (time.getMonth()+1)<10?"0"+(time.getMonth()+1):(time.getMonth()+1)+"";
            let day = time.getDate()<10?"0"+time.getDate():time.getDate()+"";
            let hour = time.getHours()<10?"0" + time.getHours() : time.getHours();
            let minu = time.getMinutes()<10?"0" + time.getMinutes() : time.getMinutes();
            this.dataName = year+month+day+hour+minu+'-';

            this.autoName();

        },
        mounted(){
            if(this.adPlatform == 'Google'){
                this.nowUrl = this.adverUrl;
                this.queryNewKeywords(this.adverUrl,'RelatedToUrlSearchParameter','url')
            }
            
        },
        methods:{
            //关闭摸态框
            closeDiloagBox(){
                this.dialogNameVisible = false;
                this.dialogPreviewVisible = false;
                if(this.focusKeywords && this.keywordsInput == ''){
                    //TODO:启用时true
                   this.dialogKeywordsVisible = true;
                }else{
                    this.dialogKeywordsVisible = false
                }
                
            },

            checkChange(event,connection){
                let check = event.target.checked;
                this.connectionCheck = {
                    CONNECTION:false,
                    FRIEND:false,
                    EXCLUDE:false
                }
                if(check){
                    this.connectionCheck[connection] = true;
                    this.editAudienceForm.relationship = connection;
                }else{
                    this.editAudienceForm.relationship = null;
                }
            },
            validHomePage(){
                if(this.editAudienceForm.relationship && !this.editAudienceForm.checkHomePage.length){
                    this.$message({ type: 'error', message:'请选择主页'});
                    return false;
                }else if(!this.editAudienceForm.relationship && this.editAudienceForm.checkHomePage.length){
                    this.$message({ type: 'error', message:'请选择关系类型'});
                    return false;
                }else{
                    return true;
                }
            },
            edit(e) {
                let input = e.target.parentNode.querySelectorAll('input')[0];
                setTimeout(() => {
                    input.focus();
                }, 0);
            },
            autoAge(){
                this.editAudienceForm.age.start = (this.editAudienceForm.age.start > 65)?65:this.editAudienceForm.age.start;
                this.editAudienceForm.age.start = (this.editAudienceForm.age.start < 13)?13:this.editAudienceForm.age.start;
                this.editAudienceForm.age.end = (this.editAudienceForm.age.end > 65)?65:this.editAudienceForm.age.end;
                if(this.editAudienceForm.age.start>this.editAudienceForm.age.end){
                    this.editAudienceForm.age.end = this.editAudienceForm.age.start;
                }
                if(this.adPlatform == 'Facebook'&& this.initEnd){
                    this.fbAudienceCount(true);
                }
                
            },
            initPlatDate(){
                this.autoName();
                if(this.adPlatform == 'Google'){
                    this.deviceDisable = true;
                    this.adverLayout.device = 'all';
                    this.editAudienceForm.addr.include = this.initGgAddr;
                    this.editAudienceForm.language = this.initGgLanguage;
                    this.newEditAudienceForm.addr.include = this.initGgAddr;
                    this.newEditAudienceForm.language = this.initGgLanguage;
                    
                }else{
                    this.deviceDisable = false;
                    this.adverLayout.device = 'all';
                    this.editAudienceForm.addr.include = this.initFbAddr;
                    this.editAudienceForm.language = this.initFbLanguage;
                    this.newEditAudienceForm.addr.include = this.initFbAddr;
                    this.newEditAudienceForm.language = this.initFbLanguage;
                }
                //this.keywordsEmpty = true;
                if(this.adPlatform == 'Facebook'){
                    this.fbAudienceCount(true)
                }
                
            },
            handleClick(data){

                if(data.name == 'first'){
                    this.AudienceType = "已保存受众";
                    this.$store.dispatch('getSavedAudience').then((res)=>{
                        this.audienceTabs[0].list = res.data.data||[];
                        this.saveNo = this.audienceTabs[0].list.length?false:true;
                    })
                }

                if(data.name == 'second'){
                    this.AudienceType = "自定义受众";
                    if(this.audienceTabs[1].list.length == 0){
                        this.$store.dispatch('getCustomAudience').then((res)=>{
                            this.audienceTabs[1].list = res.data.data||[];
                            this.diyNo = this.audienceTabs[1].list.length?false:true;
                        })
                    }
                }
                if(data.name == 'third'){
                    this.AudienceType = "类似受众";
                    if(this.audienceTabs[2].list.length == 0){
                        this.$store.dispatch('getSimilarAudience').then((res)=>{
                            this.audienceTabs[2].list = res.data.data||[];
                            this.sameNo = this.audienceTabs[2].list.length?false:true;
                        })
                    }
                }
            },
            pageListCheck(){
                this.editAudienceForm.checkHomePage = [];
                let len = this.homepageList.length;
                for (let i = 0; i < len; i++) {
                    let item = this.homepageList[i];
                    if(item.check){
                        this.editAudienceForm.checkHomePage.push(item);
                    }
                }
            },
            pushItem(list,item,exList,tips){
                let len = list.length;
                let notKeyWords = true;
                if(list == this.editAudienceForm.keywords.include || list == this.editAudienceForm.keywords.exclude){
                    notKeyWords = false;
                }
                if(len >=10 && notKeyWords){
                    this.$message({ type: 'error', message: '最多添加10项'});
                    return;
                }else if(len >=20 && !notKeyWords){
                    this.$message({ type: 'error', message: '最多添加20个关键词'});
                    return;
                }

                /*
                *如果是位置：判断key是否相等
                *否则判断 name是否相等
                */

                if(item.country || item.type == 'country' || item.type == '国家'){
                    for(let i=0;i<len; i++){
                        if(list[i].key==item.key){
                            this.$message({ type: 'error', message: item.name+'已存在,请勿重复添加'});
                            return;
                        }
                    }
                    if(exList && exList.length){
                        for(let j = 0; j<exList.length; j++){
                            if(exList[j].key == item.key){
                                this.$message({ type: 'error', message: tips+'已存在:'+item.name+'，请勿重复添加'});
                                return;
                            }
                        }
                    }
                }else{
                    for(let i=0;i<len; i++){
                        if(list[i].name==item.name){
                            this.$message({ type: 'error', message: item.name+'已存在,请勿重复添加'});
                            return;
                        }
                    }
                    if(exList && exList.length){
                        for(let j = 0; j<exList.length; j++){
                            if(exList[j].name == item.name){
                                this.$message({ type: 'error', message: tips+'已存在:'+item.name+'，请勿重复添加'});
                                return;
                            }
                        }
                    }
                }
                list.push(item);
            },
            //选择位置
            handleAddrSelect(item){
                if(this.addrType =='include'){
                    this.pushItem(this.editAudienceForm.addr.include,item,this.editAudienceForm.addr.exclude,'不包含项');
                }else{
                    this.pushItem(this.editAudienceForm.addr.exclude,item,this.editAudienceForm.addr.include,'包含项');
                }
                this.addrInput = ''
            },

            //选择关键词
            keyWordsSelect(e,item){
                let listdiv = e.target.parentElement.style.display = "none"
                item.macthType = 'BROAD';
                item.name = item.value;

                if(this.keywordsType =='include'){
                    item.type = 'INCLUDE';
                    this.pushItem(this.editAudienceForm.keywords.include,item,this.editAudienceForm.keywords.exclude,'不包含项');
                }else{
                    item.type = 'EXCLUDE';
                    this.pushItem(this.editAudienceForm.keywords.exclude,item,this.editAudienceForm.keywords.include,'包含项');
                }
                this.keywordsInput = this.preKeywordsInput;
                this.keywordsEmpty = false;
            },
            //回车关键词
            enterKeyWords(){
                if(this.keywordsInput.length >50){
                    this.$message({ type: 'error', message: '关键词不可超过50个字符'});
                    return
                }else if(this.keywordsInput.length >0){
                    if(this.keywordsType =='include'){
                        this.pushItem(this.editAudienceForm.keywords.include,{show:false,name:this.keywordsInput,value:this.keywordsInput,macthType:'BROAD',type:'INCLUDE'},this.editAudienceForm.keywords.exclude,'不包含项');
                    }else{
                        this.pushItem(this.editAudienceForm.keywords.exclude,{show:false,name:this.keywordsInput,value:this.keywordsInput,macthType:'BROAD',type:'EXCLUDE'},this.editAudienceForm.keywords.include,'包含项');
                    }
                }
                this.dialogKeywordsVisible = false;
                this.keywordsInput = "";
                this.keywordsEmpty = false;
            },
            //选择语言
            handleLanguageSelect(item){
                this.pushItem(this.editAudienceForm.language,item);
                this.languageInput = ''
            },
            ggLanguageSelect(value){
                this.ggLanguageList.forEach((n,i)=>{
                    if(n.name == value){
                        this.pushItem(this.editAudienceForm.language,n);
                        this.languageInput = ''
                    }
                })
                
            },
            //选择细分定位
            handlePositionSelect(item){
                if(this.positionType =='1'){
                    this.pushItem(this.editAudienceForm.position.include,item,this.editAudienceForm.position.exclude,'不包含项');
                }else{
                    this.pushItem(this.editAudienceForm.position.exclude,item,this.editAudienceForm.position.include,'包含项');
                }
                this.positionInput = ''
            },

            //主页列表
            queryPageList(item){
                this.$store.dispatch('getHomePageList')
                    .then((ret)=>{
                        if(ret.data && ret.data.data && ret.data.data.length){
                            let list = ret.data.data;
                            for(let i=0;i<list.length;i++){
                                list[i].check = false;
                            }
                            this.$store.commit('HOMEPAGE_LIST',{item:list})
                        }
                    })
            },

            //位置搜索
            queryAddrSearch(queryString, cb){
                // if(queryString == "" || queryString == " "){
                //     queryString = "美国"
                // }
                let params = {
                    name:queryString,
                    before:'',
                    after:'',
                    limit:10
                }

                clearTimeout(this.timer);

                this.timer = setTimeout(()=>{
                    if(queryString != "" && queryString != " "){
                        //fb--getAddr  gg--ggLocationsList
                        if(this.adPlatform == 'Facebook'){
                            this.$store.dispatch("getAddr",params)
                            .then((ret)=>{
                                if(ret.data && ret.data.data && ret.data.data.data){
                                    let list = ret.data.data.data;
                                    list.forEach((n,i)=>{
                                        n.value = n.name
                                    });
                                    cb(list);
                                }
                            })
                        }else{
                            this.$store.dispatch("ggLocationsList",params)
                                .then((ret)=>{
                                    if(ret.data && ret.data.data){
                                        let list = ret.data.data;
                                        list.forEach((n,i)=>{
                                            n.value = n.name
                                        });
                                        cb(list);
                                    }
                                })
                            }
                    }
                }, 500);
            },

            
            clearKeywordsInput(){
                this.keywordsInput = ''
            },
            initKeywordsList(){
                this.focusKeywords = true;
                if(this.keywordsInput == ""){
                    this.keyWordsSearch()
                }
            },
            //关键词搜索
            keyWordsSearch(){
                this.preKeywordsList = [];
                this.dialogKeywordsVisible = true;
                if(this.keywordsInput == ""){
                    //网址推荐关键词
                    if(this.nowUrl == this.adverUrl){
                        this.keywordsShow = this.queryedUrl? false:true;
                        this.preKeywordsList = this.urlKeywordsList || [];
                    }else{
                        this.keywordsShow = true;
                        this.nowUrl = this.adverUrl;
                        this.urlKeywordsList = [];
                        this.queryNewKeywords(this.adverUrl,'RelatedToUrlSearchParameter','url');
                    }
                }else{
                    //搜索关键词
                    this.keywordsShow = true;
                    this.queryNewKeywords(this.keywordsInput, 'RelatedToQuerySearchParameter','words')
                }
            },

            queryNewKeywords(text,type,isurl){
                let params = {
                    text,
                    type
                }
                this.$store.dispatch('ggKeyWordsList',params)
                .then((ret)=>{
                    if(ret.data && ret.data.data){
                        this.keywordsShow = false;
                        this.preKeywordsInput = this.keywordsInput;
                        let list = ret.data.data;
                        list.forEach((n,i)=>{
                            n.show = false;
                            // n.newValue = highLighted(this.keywordsInput,n.value)
                        });
                        if(isurl == 'url'){
                            this.urlKeywordsList = list;
                            this.preKeywordsList = list;
                            this.queryedUrl = true;
                        }else{
                            this.preKeywordsList = list
                        }
                        
                    }else{
                        this.keywordsShow = false;
                    }
                })
            },

            //语言搜索
            queryLanguageSearch(queryString, cb){
                if(queryString == "汉语"){
                    queryString = "中文"
                }
                let params = {
                    name:queryString
                }
                clearTimeout(this.timer);

                this.timer = setTimeout(()=>{
                    if(queryString != "" && queryString != " "){
                    this.$store.dispatch('getLanguage',params)
                        .then((ret)=>{
                            if(ret.data && ret.data.data){
                                let list = ret.data.data;
                                list.forEach((n,i)=>{
                                    n.value = n.name;
                                    n.key = n.platformFlag;
                                });
                                cb(list);
                            }
                        })
                    }
                }, 500)
            },

            //细分定位搜索--建议列表
            queryPositionSearch(queryString, cb){
                let params = {
                    name:queryString
                }

                let optimizeFor = 'LINK_CLICKS';
                switch(this.adverPlan){
                    case "访问量":
                    optimizeFor = 'LINK_CLICKS';
                    break;
                    case "品牌知名度":
                    optimizeFor = 'BRAND_AWARENESS';
                    break;
                    case "主页赞":
                    optimizeFor = 'PAGE_LIKES';
                    break;
                }

                let suggestions = this.editAudienceForm.position.include;

                let SuParams = {
                    objective: optimizeFor,
                    suggestions: suggestions
                }

                clearTimeout(this.timer);

                this.timer = setTimeout(()=>{
                    if(queryString != "" && queryString != " "){
                    //细分定位搜索
                    this.$store.dispatch('getSearchPosition',params)
                        .then((ret)=>{
                            if(ret.data && ret.data.data){
                                let list = ret.data.data;
                                list.forEach((n,i)=>{
                                    n.value = n.name
                                });
                                cb(list);
                            }
                        })
                    }else{
                        //细分定位建议列表
                        this.$store.dispatch('getSuggestionsPosition',JSON.stringify(SuParams))
                            .then((ret)=>{
                                if(ret.data && ret.data.data){
                                    let list = ret.data.data;
                                    list.forEach((n,i)=>{
                                        n.value = n.name
                                    });
                                    cb(list);
                                }
                            })
                    }
                }, 500)
            },
            
            audienceTabsShow(){
                this.dialogNameVisible=true;
                if(this.audienceTabs[0].list.length == 0){
                    this.$store.dispatch('getSavedAudience').then((res)=>{
                        this.audienceTabs[0].list = res.data.data||[];
                        this.saveNo = this.audienceTabs[0].list.length?false:true;
                    })
                }

                //this.$store.dispatch('getAudienceTabs',{id : "1"})
            },

            //选择已有受众
            handleAudience(item,type){
                this.editAudienceForm.nameList = item;
                if(this.editAudienceForm.nameList.type == 'SAVED'){
                    this.replaceBtnShow = true;
                }else{
                    this.replaceBtnShow = false;
                }

                if(this.AudienceType == "已保存受众"){
                    //替换form表单
                    let content = JSON.parse(item.content);
                    this.editAudienceForm.age.start = content.minAge;
                    this.editAudienceForm.age.end = content.maxAge;
                    this.editAudienceForm.gender = content.gender;
                    this.editAudienceForm.language = content.locales || [];
                    this.editAudienceForm.position.include = content.suggestions || [];
                    this.editAudienceForm.position.exclude = content.exclusedSuggestions || [];
                    this.editAudienceForm.relationship = content.connectionType;
                    this.editAudienceForm.checkHomePage = content.pageConnections || [];
                    this.editAudienceForm.addr.include = content.places || [];
                    this.editAudienceForm.addr.exclude = content.excludePlaces || [];

                    if(content.pageConnections && content.pageConnections.length){
                        let list = content.pageConnections;
                        for(let i = 0; i < list.length; i++){
                            this.homepageList.forEach((n)=>{
                                if(n.id == list[i].id){
                                    n.check = true;
                                }
                            })
                        }
                    }
                }
                this.dialogNameVisible = false;
                //受众数量
                this.fbAudienceCount(true)
            },
            //自动名称
            autoName(){
                this.editAudienceForm.name = this.dataName + "受众";
            },
            Autocomplete(){
                if(this.editAudienceForm.name) return;
                this.autoName()
            },
            replaceShow(){
                if(!this.validPlaceTips()){
                    return;
                }
                if(!this.validHomePage()){
                    return;
                }
                this.dialogReplaceVisible = true;
            },
            saveShow(){
                if(!this.validPlaceTips()){
                    return;
                }
                if(!this.validHomePage()){
                    return;
                }
                this.dialogSaveVisible = true;
            },

            validPlaceTips(){
                let par = this.setParams();
                if(!par.places.length){
                    // this.$message({ type: 'error', message:'受众位置不能为空！'});
                    this.keywordsEmpty = true;
                    return false;
                }else{
                    return true;
                }
            },

            //保存受众参数
            setParams(){
                let gender = null;
                if(this.editAudienceForm.gender === ""){
                    gender = null;
                }else{
                    gender = this.editAudienceForm.gender;
                }
                return {
                    name:this.editAudienceForm.name,
                    audiences:this.editAudienceForm.nameList.id?[{
                        id:this.editAudienceForm.nameList.id,
                        name:this.editAudienceForm.nameList.name
                    }]:[],
                    maxAge:this.editAudienceForm.age.end,
                    minAge:this.editAudienceForm.age.start,
                    gender: gender,
                    locales:this.editAudienceForm.language||[],
                    suggestions:this.editAudienceForm.position.include||[],
                    exclusedSuggestions:this.editAudienceForm.position.exclude||[],
                    connectionType:this.editAudienceForm.checkHomePage.length?this.editAudienceForm.relationship:null,
                    pageConnections:this.editAudienceForm.checkHomePage||[],
                    places:this.editAudienceForm.addr.include||[],
                    exclusedPlaces:this.editAudienceForm.addr.exclude||[],
                    reach: this.editAudienceForm.reach
                }
            },

            //替换已有受众
            replaceAudience(){
                if(!this.validHomePage()){
                    return;
                }
                this.isLoading = true;
                this.editAudienceForm.name = this.editAudienceForm.nameList.name;
                let par = this.setParams();
                par.localId = this.editAudienceForm.nameList.localId;

                let params = JSON.stringify(par)
                this.$store.dispatch("updateSaveAudience",params)
                    .then((res)=>{
                        this.isLoading = false;
                        if(res.data && res.data.success) {
                                this.$message({
                                    type: 'success',
                                    message: '替换受众成功!'
                                });
                            }
                    })
                
                this.dialogReplaceVisible = false;
                this.isSaved = true;
            },
            //保存新受众
            saveAudience(){
                if(!this.validHomePage()){
                    return;
                }
                this.isLoading = true;
                if(this.editAudienceForm.name === ''){
                    this.requireName = true;
                    return;
                }
                let par = this.setParams();
                

                /**
                **如果有id则调用替换接口
                **否则调用新增接口
                **/

                if(this.audienceId){
                    par.localId = this.audienceId;
                    let params = JSON.stringify(par)
                    this.$store.dispatch("updateSaveAudience",params)
                    .then((res)=>{
                        this.isLoading = false;
                        if(res.data && res.data.success) {
                                this.$message({
                                    type: 'success',
                                    message: '保存受众成功!'
                                });
                            }
                    })
                }else{
                    let params = JSON.stringify(par)
                    this.$store.dispatch("createSaveAudience",params)
                    .then((res)=>{
                        this.isLoading = false;
                        if(res.data && res.data.success) {
                            this.audienceId = res.data.data;
                            this.$message({
                                type: 'success',
                                message: '保存受众成功!'
                            });
                        }
                    })
                }

                this.dialogSaveVisible = false;
                this.isSaved = true;

            },
            //关闭选择的tag
            closeListTag(i,type){
                switch(type){
                    case 'name':
                        this.editAudienceForm.nameList={};
                        this.autoName();
                        this.editAudienceForm = this.newEditAudienceForm;
                        this.replaceBtnShow = false;
                        break;
                    case 'addrinclude':this.editAudienceForm.addr.include.splice(i,1);break;
                    case 'addrexclude':this.editAudienceForm.addr.exclude.splice(i,1);break;
                    case 'keywordsinclude':this.editAudienceForm.keywords.include.splice(i,1);break;
                    case 'keywordsexclude':this.editAudienceForm.keywords.exclude.splice(i,1);break;
                    case 'language':this.editAudienceForm.language.splice(i,1);break;
                    case 'positioninclude':
                        this.editAudienceForm.position.include.splice(i,1);
                        this.extendTree(this.positionPreviewTree);
                        break;
                    case 'positionexclude':
                        this.editAudienceForm.position.exclude.splice(i,1);
                        this.extendTree(this.positionExcludePreviewTree);
                        break;
                    case 'system' : this.adverLayout.systemInclude.splice(i,1);break;
                }
            },
            getFbCount(init){
                let optimizeFor = "";
                let position = [];
                switch(this.adverPlan){
                    case "访问量":
                    optimizeFor = 'LINK_CLICKS';
                    break;
                    case "品牌知名度":
                    optimizeFor = 'BRAND_AWARENESS';
                    break;
                    case "主页赞":
                    optimizeFor = 'PAGE_LIKES';
                    break;
                }
                switch(this.adverLayout.device){
                    case "pc":
                    position = {
                       devicePlatforms: ["DESKTOP"]
                    }
                    break;
                    case "mb":
                    position = {
                       devicePlatforms: ["MOBILE"]
                    }
                    break;
                    default:
                    position = {
                       devicePlatforms: ["DESKTOP","MOBILE"]
                    }
                }

                let audience = this.setParams();
                
                let newParam = {
                    optimizeFor: optimizeFor,
                    currency: 'CNY',
                    position: position,
                    savedAudience: audience
                };

                let params = JSON.stringify(newParam);
                this.$store.dispatch('getAudienceCount',params)
                    .then((res) => {
                        this.nexting = false;
                        this.initEnd = true;
                        if(res.data && res.data.data){
                            let item = {
                                pcCount: "",
                                mobileCount: "",
                                allCount: res.data.data.user //总覆盖人数
                            }
                            this.$store.commit("AUDIENCE_COUNT_TIPS", {item})
                            this.editAudienceForm.reach = res.data.data.user;
                            
                            let data = {
                                amountMin: res.data.data.amountMin,//最小建议竞价
                                amountMax: res.data.data.amountMax,//最大建议竞价
                                amountMedian: res.data.data.amountMedian//建议竞价
                            }
                            this.$store.commit("BUDGET_AMOUNT", {data})
                            if(!init) this.nextCommit();
                        }
                    })
            },

            //fb获取受众数量
            fbAudienceCount(init){
                if(this.type != 'new'){
                    return;
                }
                if(!this.validPlaceTips()){
                    return;
                }

                clearTimeout(this.timer);

                this.timer = setTimeout(()=>{
                    this.getFbCount(init)
                }, 500)

            },

            //gg获取受众数量
            ggAudienceCount(init){
                if(this.type != 'new'){
                    return;
                }
                console.log(this.editAudienceForm.addr.include)

                let newParam = {
                    audience:{
                        languages: this.editAudienceForm.language,
                        keyWords: this.editAudienceForm.keywords.include,
                        exclusedKeyWords: this.editAudienceForm.keywords.exclude,
                        places: this.editAudienceForm.addr.include ||null
                    },
                    budget:{
                        isAutoBid:null,
                        bidAmount:null,
                        budgetAmount:null
                    }
                }
                let params = JSON.stringify(newParam);
                this.$store.dispatch('getEsimate',params)
                    .then((res) => {
                        this.nexting = false;
                        this.initEnd = true;
                        if(res.data && res.data.data){
                            let item = res.data.data;
                            this.$store.commit("GGAUDIENCE_COUNT_TIPS", {item})
                            if(!init) this.nextCommit();
                        }
                    })

            },

            nextCommit(){
                let item = [
                    {
                        created:true,
                        click:true,
                        style:"li-created",
                        step:'2',
                        title:"选择受众",
                        info:"",
                        icon:'el-icon-check'
                    }
                ]
                this.$store.commit('ADSTEP_LIST_CREATED', {item});
                this.$store.commit('ACTIVE_STEP', {step:"3"});
                if(!this.stepCreated){
                    this.$store.commit('CREATED_STEP', {step:"3"});
                    this.stepCreated = true;
                }
            },


            //下一步
            nextStep(){
                this.keywordsEmpty = true;
                
                if(this.adPlatform == 'Google'){
                    if(this.editAudienceForm.keywords.include.length ==0) return;
                    if(this.editAudienceForm.language.length ==0) return;
                }

                if(this.adPlatform == 'Facebook'){
                    if(!this.validHomePage()){
                        return;
                    }
                    this.nexting = true;
                    this.fbAudienceCount(false);
                }else if(this.adPlatform == 'Google'){
                    this.nexting = true;
                    this.ggAudienceCount(false);
                }

                
            },

            getTreeJson(){
                this.dialogPreviewVisible=true;
                this.positionPreviewTree = [];
                this.positionExcludePreviewTree = [];
                this.positionShow = true;
                this.getPositionTree();
            },

            getPositionTree(){
                this.$store.dispatch('getAllPosition')
                    .then((ret)=>{
                        this.positionShow = false;
                        if(ret && ret.data && ret.data.data){
                            let list = ret.data.data.children;
                            let item = ret.data.data.children;
                            //判断checked
                            this.extendTree(list);
                            this.positionPreviewTree = list;
                            this.extendTree(item);
                            this.positionExcludePreviewTree = item;
                        }
                    })
            },

            pushPositionItem(list,data){
                let len = list.length;
                if(len ==0){
                    list.push(data);
                }else{
                    let have = false;
                    let n = 0;
                    for(let i = 0;i<len;i++){
                        if(list[i].name == data.name){
                            have = true;
                            n = i;
                        }
                    }
                    if(have){
                        list.splice(n,1)
                    }else{
                        list.push(data);
                    }
                }
            },

            checkPosition(store, data,node,event){
                //data.name = data.targeting.name;
                if(this.positionType == "1"){
                    this.pushPositionItem(this.editAudienceForm.position.include,data.targeting)
                }else if(this.positionType == "2"){
                    this.pushPositionItem(this.editAudienceForm.position.exclude,data.targeting)
                }
            },

            //深度递归遍历positionPreviewTree
            extendTree(data){
                let include = this.editAudienceForm.position.include;
                let exclude = this.editAudienceForm.position.exclude;
                let item = this.positionType == '1'?include : exclude;
                data.forEach((n)=>{
                    n.checked = false;
                    n.disable = false;
                    if(n.targeting){
                        //checked属性
                        for(let i = 0; i < item.length; i++){
                            if(item[i].name == n.path){
                                n.checked = true;
                            }
                        }
                        //disable属性
                        if(this.positionType == '1'){
                            for(let i = 0; i < exclude.length; i++){
                                if(exclude[i].name == n.path){
                                    n.disable = true;
                                }
                            }
                        }else{
                            for(let i = 0; i < include.length; i++){
                                if(include[i].name == n.path){
                                    n.disable = true;
                                }
                            }
                        }
                    }else{
                        this.extendTree(n.children)
                    }
                })
            },

            /***
                如果有targeting 才渲染checkbox
                如果checked 则加载选中
                如果disable 则不可选中
            **/
            renderContent(h, { node, data, store }) {
                if(data.targeting){ 
                    //如果checked 则加载选中
                    if(data.checked){
                        return (
                            <span>
                              <span>
                                <span>{node.label}</span>
                              </span>
                              <span style="float: right; margin-right: 15px">
                                <el-checkbox checked on-change={ () => this.checkPosition(store, data,node,event) }></el-checkbox>
                              </span>
                            </span>
                        );
                    }else if(data.disable){
                        return (
                            <span>
                              <span>
                                <span>{node.label}</span>
                              </span>
                              <span style="float: right; margin-right: 15px">
                                <el-checkbox disabled on-change={ () => this.checkPosition(store, data,node,event) }></el-checkbox>
                              </span>
                            </span>
                        );
                    }else{
                        return (
                            <span>
                              <span>
                                <span>{node.label}</span>
                              </span>
                              <span style="float: right; margin-right: 15px">
                                <el-checkbox on-change={ () => this.checkPosition(store, data,node,event) }></el-checkbox>
                              </span>
                            </span>
                        );
                    }
                    
                }else{
                    return (
                            <span>
                          <span>
                            <span>{node.label}</span>
                          </span>
                          <span style="float: right; margin-right: 5px">
                          </span>
                        </span>
                    );
                }

            }
        }
    }
</script>

<style lang="scss" scoped>
    $blackBorder: #ddd;
    $gray:#999999;
    $wihte:#fff;
    $fontColor:#000;
    $hoverBgColor:#f4f7f9;
    $MainColor: #0686F9;
    $disabelColor: #666666;
    $mainBorder: #EAEEF0;
    $inputBorder:#D5DFE4;
    $linkColor:#0686F9;
    $includeColor:#6CD858;
    $excludeColor:#FF3526;
    $tagbgColor:#E6F2FE;
    $hovertagbgColor:#CDE7FE;
    $errorColor:#FF3526;
    

    .high-lighted-tips{
        color:$linkColor;
    }
    .keywords-list{
        height: 34px;
        line-height: 34px;
        cursor: pointer;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .keywords-list:hover{
        background: #E4E8F1;
    }

    .key-item{
        
        height: 34px;
        line-height: 34px;
        padding-left: 10px;
        cursor: pointer;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .key-value{
        float:left;
        width:55%;
    }
    .key-comper{
        width:32%;
        float:right;
        color: $gray;
    }

    .no-audence{
        height:50px;
        line-height:50px;
        text-align:center;
        color:$gray;
        font-size:10px;
    }
    .required-tip{
        color:$errorColor
    }
    .required-label{
        width: 100px;
        text-align:right
    }
    .more-required-label{
        width: 90px;
        text-align:right
    }
    .adv-tag{
        margin-bottom:5px;
        margin-right:3px;
        height: 26px;
        line-height: 24px;
    }
    .adv-tag:hover{
        color:$disabelColor !important;
    }
    .name-tag{
        position:absolute;
        top:4px;
        height:26px;
        line-height:26px;
        display:inline-block;
        max-width:350px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .name-tag:hover{
        color:$disabelColor !important;
    }
    .audience-container{
        padding: 10px 0;
        text-align: left;
    }
    .adv-form-item{
        margin-bottom:16px;
    }
    .more-form-item{
        width: 520px;
        border-radius: 4px;
        margin-left: 90px;
        padding-top:5px;
    }
    .audience-tips{
        height: 30px;
        line-height: 30px;
        border-bottom:1px solid $mainBorder;
        margin-bottom: 10px;
        color: $gray;
        font-size: 12px;
    }
    .name-tag-box{
        border:1px solid $inputBorder;
        border-radius:4px;
        cursor: text;
        padding:0 10px;
        height: 32px;
        width: 376px;
    }
    .name-tag-icon{
        cursor:pointer;
        float:right;
        position:relative;
        top:12px;
        right:0px;
        font-size:10px;
        color:$gray;
    }
    .dialog-name-box{
        position: absolute;
        z-index: 1000;
        margin-top: 3px;
        width: 386px;
        background: $wihte;
        border: 1px solid $mainBorder;
        box-shadow: 0px 8px 12px 0px rgba(0,0,0,0.10);
        border-radius: 4px;
        
        overflow: auto
    }
    .dialog-preview-box{
        position: absolute;
        left:110px;
        z-index: 1000;
        margin-top: 3px;
        width: 400px;
        background: $wihte;
        border: 1px solid $mainBorder;
        box-shadow: 0px 8px 12px 0px rgba(0,0,0,0.10);
        border-radius: 4px;
        max-height: 350px;
        overflow: auto
    }
    .dialog-keywords-box{
        position: absolute;
        left:100px;
        z-index: 1000;
        margin-top: 3px;
        width: 320px;
        background: $wihte;
        border: 1px solid $mainBorder;
        box-shadow: 0px 8px 12px 0px rgba(0,0,0,0.10);
        border-radius: 4px;
        max-height: 250px;
        overflow: auto
    }
    .adv-tooltip{
        text-align: left;
    .tooltip-name{
        margin-bottom: 5px;
        width: 190px;
        span{
            word-wrap:break-word
        }
    }
    .tooltip-label{
        height: 20px;
        line-height: 20px;
        color: $gray;
    }
    }

    .active-row{
        cursor: pointer;
        height: 32px;
        line-height: 32px;
        .audience-info:after{
            content:".";
            display:block;
            height:0;
            clear:both;
            visibility:hidden;
        }
    .active-name{
        padding-left:10px;
        height:30px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .active-type{
        text-align:right;
        padding-right:10px;
        color: $gray;
        height:30px;
    }
    }
    .active-row:hover{
        background: $hoverBgColor;
    }

    .icon-location-include{
        color:$includeColor;
    }
    .icon-location-uninclude{
        color:$excludeColor;
    }

    .inline-input{
        height: 28px;
        line-height: 28px;
        width: 250px;
    }
    .inline-input-big{
        height: 28px;
        line-height: 28px;
        width: 400px;
    }
    .band-box{
        min-height: 50px;
    }
    .band-box-tip{
        color: $gray;
    }
    .band-box-inner{
        background: $hoverBgColor;
        padding-left:10px;
    }
    .col-label{
        text-align:right;
        padding-right:10px;
    }
    .device-radio{
        width:120px;
    }
    .dropdown-link{
        width: 170px;
        border-bottom:1px solid $inputBorder;
        cursor: pointer;
    }
    .dropdown-card{
        width: 170px;

    }
    .dropdown-card-list{
        border-bottom:1px solid $inputBorder;
    }
    .dropdown-disable{
        color:$disabelColor;
        opacity: 0.5;
    }
    .dropdown-card-title{
        display: inline-block;
        width: 140px;
    }
    .append-btn{
        display: block;
        position: absolute;
        left: 445px;
        top: 3px;
        float: left;
    span{
        display: inline-block;
        height: 26px;
        line-height: 26px;
    }
    .pre-view{
        cursor: pointer;
        font-size: 12px;
        height:20px;
        line-height:20px;
        color: $linkColor;
        margin-left: 8px;
        padding-left:8px;
        border-left:1px solid $inputBorder;
    }
    }
    .tag-border-top{
        border-top:1px solid #D5DFE4;
        margin-top:10px;
        padding-top:10px;
    }
    .tag-box-border{
        width: 644px;
        border:1px solid $inputBorder;
        padding:16px;
        border-radius: 4px;
        margin-left: 100px;
    }
    .tag-box-error{
        border:1px solid $errorColor;
    }
    .more-box-border{
        width: 644px;
        background: $hoverBgColor;
        padding:16px;
        margin-top:10px;
        border-radius: 4px;
        margin-left: 100px;
    }
    .location-tips{
        float: left;
        position: relative;
        left: 785px;
        font-size: 12px;
        width: 130px;
        height: 0;
        color:$errorColor;
    }
    .tag-box-homepage{
        width: 520px;
        height: 100px;
        padding:5px;
        background:$wihte;
        overflow: auto;
        border: 1px solid $inputBorder;
        border-radius: 4px;
    }
    .homepage-tag{
        display:block;
        height: 28px;
        line-height: 28px;
        width:99%;
        overflow:hidden;
    }
    .tag-line{
        border-bottom:1px solid $mainBorder;
        margin: 10px 0;
    }
    .tag-line-black{
        border-bottom:1px solid $inputBorder;
        margin-bottom: 10px;
        margin-top: 5px;
    }
    .tag-box:after{
        content:".";
        display:block;
        height:0;
        clear:both;
        visibility:hidden;
    }
    .label-title{
        color:$gray;
        display:inline-block;
        vertical-align:top;
        margin:3px 8px 0;
    }
    .tag-box-title{
        max-width: 70px;
        color:$disabelColor;
        width: inherit;
    }
    .tag-box-inner{
        min-height: 36px;
    span{
        margin-right: 3px;
    }
    }

    .more-setting{
        background:$hoverBgColor;
    }


    .form-row{
        margin-bottom: 16px;
        width:400px;
    }
    .form-label{
        display: inline-block;
        width:100px;
        text-align: right;
        margin-right: 5px;
        font-size: 14px;
        color: $disabelColor;
        vertical-align:top;
    }
    .require-name-tip{
        display:block;
        position:relative;
        height:0;
        top:-20px;
        float:left;
        font-size:10px;
        margin-left:43%;
        color:$errorColor;
    }

    .btn-common {
        margin-left: 10px;
    }
    .tip-wrapper {
        display: inline-block;
        padding: 0 20px;
    .tip-left {
        width: 35px;
        color: #FFC000;
        font-size: 25px;
        float: left;
        text-align: center;
        margin-right: 10px;
    }
    .tip-right {
        float: left;
    .tip-title {
        float: left;
        width: 100%;
        font-size: 14px;
        color: $disabelColor;
        line-height: 30px;
    }
    .tip-txt {
        float: left;
        font-size: 12px;
        color: $disabelColor;
        line-height: 28px;
    }
    }
    }

    .adc-tips {
        line-height: 8px;
        color: #999;
        font-size: 12px;
        background: transparent
    }
    .string-count-tip {
        position: relative;
        text-align:center;
        float: right;
        right: 50px;
        top: 2px;
        display: inline-block;
        width: 20px;
        height: 24px;
        vertical-align: middle;
        line-height: 28px;
    }
    .bd-next-btn{
        width: 120px;
        height: 34px;
        border: none;
        border-radius: 34px;
        color: white;
        background-color: #ffb100;
    }
    .bd-next-btn:hover {
        background: #E59E00;
    }
    .no-homepage{
        padding: 10px 10px;
        color: #999;
        font-size: 12px;
        a{
            color: #0686F9;
            text-decoration: underline;
        }
    }
    .position-autocomplete{
        li{
            line-height:49px;
        }
    }

</style>